import { getArticleDetail, getArticleList } from '@/services';
import { IArticleDetail, IArticleItem } from '@/types';
import { Effect, Reducer } from 'umi';

export interface ArticleModelState {
  articleList: IArticleItem [];
  articleLength: number;
  articleDetail: Partial<IArticleDetail>; // 把接口的属性变成可选的
}

export interface ArticleModelType {
  namespace: 'article';
  state: ArticleModelState;
  effects: {
    getArticleList: Effect;
    getArticleDetail: Effect;
  };
  reducers: {
    save: Reducer<ArticleModelState>;
  };
}

const ArticleModel: ArticleModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'article',

  // 数据模型状态，相当于vuex的state
  state: {
    articleList: [],
    articleLength: 0,
    // articleDetail: {} as IArticleDetail // 强制类型推断
    articleDetail: {}
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *getArticleList({payload}, {call, put, select}){
      let {articleList} = yield select((state:{article: ArticleModelState})=>state.article);
      let result = yield call(getArticleList, payload);
      if (result.data){
        let list = result.data[0];
        if (payload !== 1){
          list = [...articleList, ...list];
        }
        yield put({
          type: 'save',
          payload: {
            articleList: list,
            articleLength: result.data[1]
          }
        })
      }
    },
    *getArticleDetail({payload}, {call, put}){
      let result = yield call(getArticleDetail, payload);
      if (result.data){
        yield put({
          type: 'save',
          payload: {
            articleDetail: result.data
          }
        })
      }
    }
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

  }
};

export default ArticleModel;
